#import "DataType.h"
#import "BuffManager.h"

@implementation Buff

@synthesize bType=mType;

-(id)initWithSpell:(Spell*)spell
{
	if ((self = [super init])) {
		[self autorelease];
		
		mAlreadyBlink = false;
		mType = spell.sType;
		
		mIcon = [CCSprite spriteWithSpriteFrameName:spell.fileName];
		mIcon.scale = 0.7;
		[self addChild:mIcon];
		
		mLastTime = [CCLabelTTF labelWithString:@"" fontName:gFontName fontSize:16];
		mLastTime.color = ccYELLOW;
		mLastTime.position = ccp(0,-25);
		[self addChild:mLastTime];
		
		mMaxTime = spell.duration;
		mCurTime = 0;
		
		mLastTime.string = [NSString stringWithFormat:@"%ds", mMaxTime];
	}
	return self;
}
	
-(bool)updateBuff:(ccTime)dt
{
	mCurTime += dt;
		
	if(mCurTime >= mMaxTime)
		return true;
	else if(mCurTime >= mMaxTime-3 && !mAlreadyBlink) {
		[mIcon runAction:[CCRepeatForever actionWithAction:[CCSequence actions:[CCFadeTo actionWithDuration:0.4 opacity:50],[CCFadeTo actionWithDuration:0.4 opacity:255], NULL]]];
		mAlreadyBlink = true;
	}
	
 	mLastTime.string = [NSString stringWithFormat:@"%ds", MAX(0, (int)(mMaxTime - mCurTime))];
		
	return false;
}
	
@end


@implementation BuffManager

static int sBuffDistance = 40;

-(id)init
{
	if ((self = [super init])) {
		[[CCTextureCache sharedTextureCache] addImage:[NSString stringWithFormat:@"spells%@.png", gHDSuffix]];
		[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:[NSString stringWithFormat:@"spells%@.plist", gHDSuffix]];
	
		self.position = ccp(205,295);
		mBuffs = [[NSMutableArray alloc] init];
	}
	return self;
}

-(void)addBuff:(Spell*)spell
{
	Buff* newBuff = [[Buff alloc] initWithSpell:spell];
	
	// Search buff exist
	bool bFound = false;

	for(uint i=0; i<[mBuffs count]; i++) {
		Buff* buff = [mBuffs objectAtIndex:i];
		if(buff.bType == spell.sType) {
			[self removeChild:buff cleanup:YES];
			[mBuffs replaceObjectAtIndex:i withObject:newBuff];
			bFound = true;
			break;
		}
	}
	
	if(!bFound) {
		newBuff.position = ccp([mBuffs count] * sBuffDistance, 0);
		[mBuffs addObject:newBuff];
	}
	[self addChild:newBuff];
}

-(void) updateBuff:(ccTime)dt
{
	int startPosX = 0;

	for(uint i=0; i<[mBuffs count];) {
		Buff* buff = [mBuffs objectAtIndex:i];
		if([buff updateBuff:dt]) {
			[self removeChild:buff cleanup:YES];
			[mBuffs removeObjectAtIndex:i];
		} else {
			buff.position = ccp(startPosX, 0);
			startPosX += sBuffDistance;
			i++;
		}
	}
}

-(void)dealloc
{
	[mBuffs release];
	[super dealloc];
}

@end
